package com.hm.service.service.spark.model;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.hm.service.utils.spark.BigModelUtils;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.concurrent.CountDownLatch;


/**
 * <a href="https://xinghuo.xfyun.cn/">科大讯飞星火认知大模型</a>
 */
@Service
public class BigModelService implements IBigModelService {
    private static final Logger logger = LoggerFactory.getLogger(BigModelService.class);

    @Qualifier("OkHttpClient")
    private final OkHttpClient okHttpClient;

    public BigModelService(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    @Override
    public String question(String problem) {
        try {
            //用来标记是否完成
            CountDownLatch latch = new CountDownLatch(1);
            //内容的拼接
            StringBuilder strBuilder = new StringBuilder();
            String authUrl = BigModelUtils.getAuthUrl();
            Request request = new Request.Builder().url(authUrl).build();
            WebSocket webSocket = okHttpClient.newWebSocket(request, new WebSocketListener() {

                @Override
                public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
                    super.onOpen(webSocket, response);
                    logger.info("onOpen--连接成功");
                }

                @Override
                public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
                    super.onMessage(webSocket, text);
                    //解析数据
                    JSONObject jsonObject = (JSONObject) JSON.parse(text);
                    JSONObject payload = jsonObject.getJSONObject("payload");
                    JSONObject choices = payload.getJSONObject("choices");
                    String status = choices.getString("status");
                    JSONArray textList = choices.getJSONArray("text");
                    for (Object object : textList) {
                        JSONObject textObj = (JSONObject) object;
                        String string = textObj.getString("content");
                        strBuilder.append(string);
                    }
                    //表示回答完毕
                    if (status.equals("2")) {
                        latch.countDown();
                        logger.info("onMessage--->:" + strBuilder);
                    }
                }

                @Override
                public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) {
                    super.onFailure(webSocket, t, response);
                    latch.countDown();
                    logger.info("onFailure--会话失败");
                }

                @Override
                public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
                    super.onClosed(webSocket, code, reason);
                    latch.countDown();
                    logger.info("onClosed--会话关闭");
                }
            });
            String reply = BigModelUtils.requestGenerator(problem);
            webSocket.send(reply);
            //等待回复完成
            latch.await();
            webSocket.close(1000, "");//关闭长连接,释放资源
            return strBuilder.toString();
        } catch (Exception e) {
            logger.error("Exception:" + e.getMessage());
        }
        return "";
    }

}
